<!-- src/views/Permission/component/role.vue -->
<template>
  <div class="role-management">
    <h2>角色管理</h2>

    <!-- 搜索表单 -->
    <el-form :model="searchForm" inline>
      <el-form-item label="角色名">
        <el-input
          v-model="searchForm.roleName"
          placeholder="请输入角色名"
          clearable
          @keyup.enter="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-button type="primary" @click="handleAddRole" icon="Plus">新增角色</el-button>

    <!-- 表格 -->
    <el-table
      :data="roleStore.roles"
      style="width: 100%; margin-top: 20px;"
      border
      v-loading="roleStore.loading"
      stripe
    >
      <el-table-column prop="id" label="角色ID" width="180" align="center"></el-table-column>
      <el-table-column prop="roleName" label="角色名" width="120" align="center"></el-table-column>
      <el-table-column prop="roleLogo" label="角色标识" width="120" align="center"></el-table-column>
      <el-table-column prop="roleDes" label="角色描述" width="180" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" align="center">
        <template #default="{ row }">
          {{ row.createTime ? row.createTime.replace('T', ' ') : '' }}
        </template>
      </el-table-column>
      <el-table-column label="权限" width="200" align="center">
        <template #default="{ row }">
          <div v-if="row.permissions && row.permissions.length > 0">
            <el-tag
              v-for="permission in row.permissions"
              :key="permission.id"
              size="small"
              style="margin: 2px;"
              closable
              @close="handleUnassignPermission(row, permission)"
            >
              {{ permission.permissionName }}
            </el-tag>
          </div>
          <span v-else>无权限</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" align="center" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)" type="primary">编辑</el-button>
          <el-button
            size="small"
            @click="handleToggleStatus(row)"
            :type="row.status === 1 ? 'danger' : 'success'"
          >
            {{ row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          <el-button size="small" @click="handleAssignPermissions(row)">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="roleStore.total"
      style="margin-top: 20px; text-align: right;"
    ></el-pagination>

    <!-- 弹窗表单 -->
    <el-dialog
      :title="operationType === 'add' ? '新增角色' : '编辑角色'"
      v-model="dialogFormVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="form"
        :rules="formRules"
        label-width="80px"
        label-position="right"
      >
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="form.roleName" :disabled="operationType === 'edit'" />
        </el-form-item>
        <el-form-item label="角色标识" prop="roleLogo">
          <el-input v-model="form.roleLogo" />
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDes">
          <el-input v-model="form.roleDes" type="textarea" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分配权限弹窗 -->
    <el-dialog
      title="分配权限"
      v-model="assignPermissionDialogVisible"
      width="600px"
    >
      <el-form label-width="80px">
        <el-form-item label="角色">
          {{ selectedRoleName }}
        </el-form-item>
        <el-form-item label="权限选择">
          <el-checkbox-group
            v-model="selectedPermissionIds"
            :loading="loadingPermissions"
            style="display: flex; flex-wrap: wrap;"
          >
            <el-checkbox
              v-for="permission in allPermissions"
              :key="permission.id"
              :label="permission.id"
              style="width: 50%; margin-bottom: 10px;"
            >
              {{ permission.permissionName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelAssignPermissions">取消</el-button>
        <el-button type="primary" @click="confirmAssignPermissions">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoleStore } from '@/stores/role'
import { ElMessage, ElMessageBox } from 'element-plus'

const roleStore = useRoleStore()

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索相关
const searchForm = ref({
  roleName: ''
})

// 表单弹窗控制
const dialogFormVisible = ref(false)
const form = ref({
  roleName: '',
  roleLogo: '',
  roleDes: '',
  status: 1
})

// 表单验证规则
const formRules = {
  roleName: [
    { required: true, message: '请输入角色名', trigger: 'blur' }
  ],
  roleLogo: [
    { required: true, message: '请输入角色标识', trigger: 'blur' }
  ]
}

// 操作类型：add / edit
const operationType = ref('add')
const editingRoleId = ref(null)

// 权限分配相关
const assignPermissionDialogVisible = ref(false)
const selectedRoleId = ref(null)
const selectedRoleName = ref('')
const allPermissions = ref([])
const selectedPermissionIds = ref([])
const loadingPermissions = ref(false)

// 加载数据
onMounted(() => {
  roleStore.fetchRoles(currentPage.value, pageSize.value)
})

// 新增角色
const handleAddRole = () => {
  operationType.value = 'add'
  form.value = {
    roleName: '',
    roleLogo: '',
    roleDes: '',
    status: 1
  }
  editingRoleId.value = null
  dialogFormVisible.value = true
}

// 编辑角色
const handleEdit = (row) => {
  operationType.value = 'edit'
  editingRoleId.value = row.id
  form.value = {
    roleName: row.roleName,
    roleLogo: row.roleLogo,
    roleDes: row.roleDes,
    status: row.status
  }
  dialogFormVisible.value = true
}

// 删除角色
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定删除角色 ${row.roleName} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const result = await roleStore.deleteRole(row.id)
    if (result.success) {
      ElMessage.success('删除成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 切换角色状态
const handleToggleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 1 ? '禁用' : '启用'}角色 ${row.roleName} 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const result = await roleStore.toggleRoleStatus(row.id)
    if (result.success) {
      ElMessage.success('状态切换成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '状态切换失败')
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    let result
    if (operationType.value === 'add') {
      result = await roleStore.addRole(form.value)
    } else {
      result = await roleStore.updateRole(editingRoleId.value, form.value)
    }

    if (result.success) {
      ElMessage.success('操作成功')
      dialogFormVisible.value = false
    }
  } catch (error) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 分页事件
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  if (searchForm.value.roleName.trim() !== '') {
    handleSearch(1, val)
  } else {
    roleStore.fetchRoles(currentPage.value, val)
  }
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  if (searchForm.value.roleName.trim() !== '') {
    handleSearch(val, pageSize.value)
  } else {
    roleStore.fetchRoles(val, pageSize.value)
  }
}

// 搜索功能
const handleSearch = async (page = 1, size = pageSize.value) => {
  try {
    await roleStore.searchRolesByRoleName(searchForm.value.roleName.trim(), page, size)
    currentPage.value = page
  } catch (error) {
    ElMessage.error('搜索失败: ' + error.message)
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.value.roleName = ''
  currentPage.value = 1
  roleStore.fetchRoles(currentPage.value, pageSize.value)
}

// 获取所有权限列表
const loadPermissions = async () => {
  loadingPermissions.value = true
  try {
    const permissions = await roleStore.getAllPermissions()
    allPermissions.value = permissions
  } catch (error) {
    ElMessage.error('加载权限列表失败：' + error.message)
  } finally {
    loadingPermissions.value = false
  }
}

// 处理分配权限
const handleAssignPermissions = async (row) => {
  selectedRoleId.value = row.id
  selectedRoleName.value = row.roleName

  // 加载所有权限
  await loadPermissions()

  // 设置当前角色已分配的权限
  const assignedPermissionIds = row.permissions ? row.permissions.map(p => p.id) : []
  selectedPermissionIds.value = assignedPermissionIds

  assignPermissionDialogVisible.value = true
}

// 确认分配权限
const confirmAssignPermissions = async () => {
  try {
    const result = await roleStore.assignPermissions(selectedRoleId.value, selectedPermissionIds.value)
    if (result.success) {
      ElMessage.success('权限分配成功')
      assignPermissionDialogVisible.value = false
      // 重新加载角色列表以更新权限信息
      if (searchForm.value.roleName.trim() !== '') {
        handleSearch(currentPage.value, pageSize.value)
      } else {
        await roleStore.fetchRoles(currentPage.value, pageSize.value)
      }
    }
  } catch (error) {
    ElMessage.error(error.message || '权限分配失败')
  }
}

// 取消分配权限
const cancelAssignPermissions = () => {
  assignPermissionDialogVisible.value = false
  selectedPermissionIds.value = []
}

// 解除权限绑定
const handleUnassignPermission = async (row, permission) => {
  try {
    await ElMessageBox.confirm(
      `确定要解除角色 ${row.roleName} 与权限 ${permission.permissionName} 的绑定吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const result = await roleStore.unassignPermission(row.id, permission.id)
    if (result.success) {
      ElMessage.success('权限解除成功')
      // 重新加载角色列表以更新权限信息
      if (searchForm.value.roleName.trim() !== '') {
        handleSearch(currentPage.value, pageSize.value)
      } else {
        await roleStore.fetchRoles(currentPage.value, pageSize.value)
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '解除权限失败')
    }
  }
}
</script>

<style scoped lang="scss">
.role-management {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;

  .el-table {
    margin-top: 20px;
  }

  .el-pagination {
    margin-top: 20px;
    text-align: right;
  }
}
</style>